package com.lecture.java8.excel.dyr.n.a001;

import com.alibaba.excel.EasyExcel;

import java.util.*;
import java.util.stream.Collectors;

public class ExcelFilter {

    public static void main(String[] args) {
        // 原始Excel文件路径
        String inputFilePath = "D:\\study\\tmp\\1114\\11.14草稿数据.xlsx";
        // 新的Excel文件路径
        String outputFilePath = "D:\\study\\tmp\\1114\\11.14筛选后的数据.xlsx";

        // 使用EasyExcel读取Excel文件
        List<CompanyData> allData = EasyExcel.read(inputFilePath).head(CompanyData.class).sheet().doReadSync();

        // 筛选数据
        Map<String, List<CompanyData>> dataByCode = new HashMap<>();
        for (CompanyData data : allData) {
            if (data.getYear() >= 2010 && data.getYear() <= 2023 && !data.getName().contains("*ST") && !data.getName().contains("ST")) {
                dataByCode.computeIfAbsent(data.getCode(), k -> new ArrayList<>()).add(data);
            }
        }

        // 再次过滤，确保每个code都有2010-2023的数据
        List<CompanyData> filteredData = new ArrayList<>();
        for (List<CompanyData> dataList : dataByCode.values()) {
            boolean hasAllYears = true;
            for (int year = 2010; year <= 2023; year++) {
                int finalYear = year;
                if (dataList.stream().noneMatch(d -> d.getYear().equals(finalYear))) {
                    hasAllYears = false;
                    break;
                }
            }
            if (hasAllYears) {
                filteredData.addAll(dataList);
            }
        }

        // 将筛选后的数据写入新的Excel文件
        filteredData = filteredData.stream().sorted(Comparator.comparing(CompanyData::getCode)).collect(Collectors.toList());
        EasyExcel.write(outputFilePath,CompanyData.class).sheet("Sheet1").doWrite(filteredData);
    }
}
